package cn.smartinvoke.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class HelpMethodXML {
	
	public static Document toDocument(String xml)
    {
        Document document = null;
        try
        {
            if (xml != null)
            {
                StringReader reader = new StringReader(xml);
                InputSource input = new InputSource(reader);
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//                factory.setNamespaceAware(true);
//                factory.setValidating(false);
                DocumentBuilder builder = factory.newDocumentBuilder();
                document = builder.parse(input);
            }
        }
        catch (Exception ex)
        {
            throw new RuntimeException("Error  XML type " + ex.getMessage());
        }

        return document;
    }
	public static String toString(Document document) throws IOException
    {
        String xml = null;

        try
        {
            DOMSource dom = new DOMSource(document);
            StringWriter writer = new StringWriter();
            StreamResult output = new StreamResult(writer);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
            transformer.transform(dom, output);
            xml = writer.toString();
        }
        catch (TransformerException e)
        {
            throw new IOException("Error Document as String:" + e.getMessageAndLocation());
        }
        return xml;
    }
}
